package org.iabako.server.serviceimpl.business;

import org.apache.commons.lang3.time.DateUtils;
import org.iabako.server.dao.business.InstallmentDAO;
import org.iabako.server.dao.JpaDAO;
import org.iabako.server.dao.business.QueryDefinitionDAO;
import org.iabako.shared.entity.enumeration.FinancialStatusSale;
import org.iabako.shared.iservice.business.PastInstallmentService;
import org.iabako.shared.querydefinition.SearchMotorQueryEnum;
import org.iabako.shared.querydefinition.columndefinition.*;
import org.iabako.shared.querydefinition.dto.QueryDefinitionDTO;
import org.iabako.shared.querydefinition.dto.QueryOperatorEnum;
import org.iabako.shared.querydefinition.dto.QueryResultDTO;
import org.iabako.shared.querydefinition.dto.QueryResultValue;
import org.iabako.shared.tools.GenericTools;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * Created by jose on 05/09/14.
 */

@org.springframework.stereotype.Service("pastInstallmentService")
public class PastInstallmentServiceImpl extends AbstractServiceImpl implements PastInstallmentService {

    @Autowired
    private InstallmentDAO installmentDAO;
    @Autowired
    private QueryDefinitionDAO queryDefinitionDAO;

    @Override
    protected JpaDAO getDAO() {
        return installmentDAO;
    }

    public QueryDefinitionDTO getSearchQueryDefinitionDTO(QueryDefinitionDTO qd) {
        qd.setSearchMotorQuery(SearchMotorQueryEnum.PastInstallmentSearch);

        qd.addCriteria(PastInstallmentColumnEnum.date,
                QueryOperatorEnum.LESS_THAN_OR_EQUALS,
                DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH));

        qd.addCriteria(PastInstallmentColumnEnum.pastInstallmentEnterprise, QueryOperatorEnum.EQUALS, getSessionUser().getEnterprise());

        queryDefinitionDAO.executeQueryDefinition(qd);

        qd.setCustomModifications(true);

        for (QueryResultDTO result : qd.getResults().values()) {
            QueryResultValue qrValue = new QueryResultValue();
            qrValue.setValue(FinancialStatusSale._1_inDebt);

            result.getValues().put(PastInstallmentColumnEnum.status, qrValue);
        }

        return qd;
    }

    public QueryDefinitionDTO setSearchCriteriaFromSuggest(QueryDefinitionDTO qd, Long hiddenSelectionCode, String suggestionValue) {
        if (!GenericTools.isEmpty(hiddenSelectionCode)) {
            qd.addCriteria(SaleColumnEnum.clientId, QueryOperatorEnum.EQUALS, hiddenSelectionCode);
            return qd;
        }
        return setSearchCriteriaFromSuggest(qd,
                suggestionValue,
                new ColumnDefinition[]{ClientColumnEnum.number, ClientColumnEnum.name, ClientColumnEnum.email, ClientColumnEnum.address1});
    }
}
